package com.homeos;

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.Date;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.packet.Message;

import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterFactory;
import twitter4j.conf.ConfigurationBuilder;


import com.ecs.android.facebook.Sample.FacebookConnector;
import com.ecs.android.facebook.Sample.SessionEvents;
import com.flotandroidchart.flot.FlotChartContainer;
import com.flotandroidchart.flot.FlotDraw;
import com.flotandroidchart.flot.data.PointData;
import com.flotandroidchart.flot.data.SeriesData;

import android.app.ProgressDialog;
import android.app.TabActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.TabHost;
import android.widget.Toast;
import android.widget.TabHost.TabContentFactory;
import android.widget.TabHost.TabSpec;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.ToggleButton;


public class HomeOS extends TabActivity {
	//********************* twitter
	TwitterFactory tf;
	Twitter twitter;
	
	final Runnable mUpdateTwitterNotification = new Runnable() {
        public void run() {
        	Toast.makeText(getBaseContext(), "Twitter updated !", Toast.LENGTH_LONG).show();
        }
    };
	private void init_twitter(){
	ConfigurationBuilder cb = new ConfigurationBuilder();
	cb.setDebugEnabled(true)
	  .setOAuthConsumerKey("wxBohqFYiSA4gQrr0KuQw")
	  .setOAuthConsumerSecret("23ZWWwQB5s7qFmr3Jm63Yrawu5HBfxvt08iJH8NEqeA")
	  .setOAuthAccessToken("331819144-pX14AG8GzfnYVJoLFrjkTV2by1rincb5Je9Q4aPt")
	  .setOAuthAccessTokenSecret("QHiDiy7ZhbmI0DkNjLWJsaREYjCxKrHHxkTgJ5I2uY");
	tf = new TwitterFactory(cb.build());
	 twitter = tf.getInstance();
	}
	
	private void tweet(final String txt)
	{
		Thread t = new Thread() {
		public void run() { 
		try {
		Status status = twitter.updateStatus(txt);
		mFacebookHandler.post(mUpdateTwitterNotification);
		} 
		catch (Exception e)
		{
			Log.d("TWITTER",e.toString());
		}
		} };
		 t.start();
	}
	
	// ********************* twitter
	
	
	//********************** facebook
	private static final String FACEBOOK_APPID = "161303623939100";
	private static final String FACEBOOK_PERMISSION = "publish_stream";
	private static final String FB_TAG = "FacebookSample";
	private static final String MSG = "Message from HomeOS Android App";
	private static final String ON_MSG = "Turned ON an appliance using the HomeOS App.";
	private static final String OFF_MSG = "Turned OFF an appliance using the HomeOS App and saved";
	
	private final Handler mFacebookHandler = new Handler();
	private TextView loginStatus;
	private FacebookConnector facebookConnector;
	 
	final Runnable mUpdateFacebookNotification = new Runnable() {
	        public void run() {
	        	Toast.makeText(getBaseContext(), "Facebook updated !", Toast.LENGTH_LONG).show();
	        }
	    };
	
	    @Override
		protected void onActivityResult(int requestCode, int resultCode, Intent data) {
			this.facebookConnector.getFacebook().authorizeCallback(requestCode, resultCode, data);
		}
		
	
		
		public void updateLoginStatus() {
			 facebookConnector.getFacebook().isSessionValid();
		}
		

		private String getFacebookMsg(String type,String power) {
			
			if(type=="ON_MSG") {return ON_MSG;}
			if(type=="OFF_MSG") {return OFF_MSG+" "+power+"atts";}
			return MSG + " at " + new Date().toLocaleString();
		}	
		
		public void postMessage(final String type, final String power) {
			
			
			if (facebookConnector.getFacebook().isSessionValid()) {
				postMessageInThread(type,power);
			} else {
				SessionEvents.AuthListener listener = new SessionEvents.AuthListener() {
					
					@Override
					public void onAuthSucceed() {
						postMessageInThread(type,power);
					}
					
					@Override
					public void onAuthFail(String error) {
						
					}
				};
				SessionEvents.addAuthListener(listener);
				facebookConnector.login();
			}
		}

		private void postMessageInThread(final String type, final String power) {
			Thread t = new Thread() {
				public void run() {
			    	
			    	try {
			    		facebookConnector.postMessageOnWall(getFacebookMsg(type,power));
						mFacebookHandler.post(mUpdateFacebookNotification);
					} catch (Exception ex) {
					}
			    }
			};
			t.start();
		}

		private void clearCredentials() {
			try {
				facebookConnector.getFacebook().logout(getApplicationContext());
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	//********************** facebook
	
	private static final int TREND_LENGTH = 30;
	private String username,password,host,serviceName,port;
	public static XMPPConnection connection;
	private ConnectionConfiguration connConfig;
	private TextView power1,power2,power3,power4,power5, temperature, powerusage, light;
	ToggleButton button1, button2, button3, button4, button5;
	int first_load = 0;
	
	private static final String TAG = "BroadcastTest";
	
	CheckBox fb, tw;
	
	private Intent myintent;
	public static String homeosID = "homeos@jabber.org"; 
	TabHost tabHost;
	TextView temp;
	ProgressDialog progressDialog;
	
	////////////////////////////////////////////////// CODE for Homeos app
	 @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main2);
        this.facebookConnector = new FacebookConnector(FACEBOOK_APPID, this, getApplicationContext(), new String[] {FACEBOOK_PERMISSION});
        Different_Grap_Types.window_length = TREND_LENGTH;
        Different_Grap_Types.powerlog = new double[Different_Grap_Types.window_length];
        for(int i=0; i < Different_Grap_Types.window_length; i+=1) {
        Different_Grap_Types.powerlog[i]=0.0;
        }
        
    	power2 = new TextView(this);button2 = new ToggleButton(this);
		power3 = new TextView(this);button3 = new ToggleButton(this);
		power4 = new TextView(this);button4 = new ToggleButton(this);
		power5 = new TextView(this);button5 = new ToggleButton(this);
		power1 = new TextView(this); button1 = new ToggleButton(this);
		
		fb = new CheckBox(getApplicationContext());
		tw = new CheckBox(getApplicationContext());
		powerusage = new TextView(this);
		temperature = new TextView(this);
		light = new TextView(this);
		
		powerusage.setText("0 W"); 
        temperature.setText("24 C");
        light.setText("3 Cd");
        
        power1.setText("0 W");  
        power2.setText("0 W");
        power3.setText("0 W");
        power4.setText("0 W");
        power5.setText("0 W");button1.setChecked(false);

        tabHost = (TabHost) findViewById(android.R.id.tabhost);
	tabHost.getTabWidget().setDividerDrawable(R.drawable.tab_divider);
		setTitle("HomeOS");
        
		
		
		

		setupTab(new TextView(this), "Home Monitor");
		setupTab(new TextView(this), "Control Panel");
		Intent trend;
		trend = new Intent().setClass(this, Different_Grap_Types.class);
		View tabview = createTabView(tabHost.getContext(), "Trend");
		TabHost.TabSpec spec = tabHost.newTabSpec("Trend").setIndicator(tabview).setContent(trend);
		
        tabHost.addTab(spec);  
	//	setupTab(new TextView(this), "Chart");
		
		
		progressDialog=ProgressDialog.show(this, "Contacting HomeOS...", "Loading");
		
			
        Bundle b = new Bundle();
        b.putString("subject", "test123");
        
        myintent = new Intent(this, BroadcastService.class);
        myintent.putExtras(b);
    	
        
   
        
         b = getIntent().getExtras();
        username = b.getString("username");
        password = b.getString("password");
        host=b.getString("host");
        port=b.getString("port");
        serviceName=b.getString("serviceName");
        Log.d("Rx values",host+":"+port+":"+username+password+serviceName);

      
        if(!serviceName.equals(""))
        {
        connConfig = new ConnectionConfiguration(host,Integer.parseInt(port), serviceName);
        }
        else
        {
        	connConfig = new ConnectionConfiguration(host,Integer.parseInt(port));
        }

        connConfig.setSASLAuthenticationEnabled(false);
        connection = new XMPPConnection(connConfig);
        
     

        try {
        	connection.connect();
        	connection.login(username, password);
         
        	}
        
        
        catch(Exception e){
        	Log.e("LOGIN-EXCEPTION",""+e);
        	Intent back = new Intent(this.getApplicationContext(),Home.class);
       	   startActivity(back);finish();
       	   }
        
       
       
     
        
		
        
        
		startService(myintent);
		init_twitter();
		
	
 
    }
	 
	 private void setupTab(final View view, final String tag) {
		 final TextView tv = new TextView(this);
		 final ScrollView s = new ScrollView(this);
		 final ImageView i = new ImageView(this);
		 
			View tabview = createTabView(tabHost.getContext(), tag);
		        TabSpec setContent = tabHost.newTabSpec(tag).setIndicator(tabview).setContent(new TabContentFactory() {
				public View createTabContent(String tag) {
					
					if(tag.equals("Chart"))
					{
						Button chart = new Button(getApplicationContext());
					       chart.setText("Chart");
					       chart.setOnClickListener(new View.OnClickListener() {
					             public void onClick(View v) {
					                 // Perform action on click
					            	 Intent intent = new Intent(getApplicationContext(),Different_Grap_Types.class);
					     			startActivity(intent);
					             }
					         });
						 //***************** chart stuff
						 s.addView(chart);
					        
						 //************************* chart stuff
						
					}
					if(tag.equals("Home Monitor"))
					{
						final TableLayout Tlayout1 = new TableLayout(getApplicationContext());
						
						 i.setImageResource(R.drawable.home_control);
						 
						 TableRow Trow0 = new TableRow(getApplicationContext());
						 
						 Trow0.addView(i);
						 Trow0.setGravity(Gravity.CENTER);
						 Tlayout1.addView(Trow0);
						 
				        TableRow Trow1 = new TableRow(getApplicationContext());
				        TextView textBox = new TextView(getApplicationContext()); 
				        textBox.setText("\t\tCurrent Power");textBox.setTextColor(Color.WHITE);Trow1.addView(textBox);
				        textBox.setTextSize(20);textBox.setTypeface(Typeface.DEFAULT_BOLD);
				        powerusage.setTextSize(20);powerusage.setTypeface(Typeface.DEFAULT_BOLD);
				        
				        powerusage.setTextColor(Color.WHITE);Trow1.addView(powerusage);
				        Tlayout1.addView(Trow1);
				        
				        TableRow Trow2 = new TableRow(getApplicationContext());
				        TextView textBox1 = new TextView(getApplicationContext()); 
				        textBox1.setText("\t\tTemperature");textBox1.setTextColor(Color.WHITE);Trow2.addView(textBox1);
				        textBox1.setTextSize(20);textBox1.setTypeface(Typeface.DEFAULT_BOLD);
				        temperature.setTextSize(20);temperature.setTypeface(Typeface.DEFAULT_BOLD);
				        temperature.setTextColor(Color.WHITE);Trow2.addView(temperature);
				        Tlayout1.addView(Trow2);
				        
				        TableRow Trow3 = new TableRow(getApplicationContext());
				        TextView textBox2 = new TextView(getApplicationContext()); 
				        textBox2.setText("\t\tIlluminance");textBox2.setTextColor(Color.WHITE);Trow3.addView(textBox2);
				        textBox2.setTextSize(20);textBox2.setTypeface(Typeface.DEFAULT_BOLD);
				        light.setTextSize(20);light.setTypeface(Typeface.DEFAULT_BOLD);
				        light.setTextColor(Color.WHITE);Trow3.addView(light);
				        Tlayout1.addView(Trow3);
				        
				        Tlayout1.setColumnStretchable(0, true);
				        Tlayout1.setColumnStretchable(1, true);
				        Tlayout1.setColumnStretchable(2, true);
				        TableLayout.LayoutParams tableRowParams=
				        	  new TableLayout.LayoutParams
				        	  (TableLayout.LayoutParams.FILL_PARENT,TableLayout.LayoutParams.WRAP_CONTENT);

				        	int leftMargin=0;
				        	int topMargin=20;
				        	int rightMargin=0;
				        	int bottomMargin=0;

				        	tableRowParams.setMargins(leftMargin, topMargin, rightMargin, bottomMargin);
				        	Trow0.setLayoutParams(tableRowParams);
				        	Trow1.setLayoutParams(tableRowParams);
				        	Trow2.setLayoutParams(tableRowParams);
				        	Trow3.setLayoutParams(tableRowParams);
				        	
				       
				        //Tlayout1.setPadding(50, 50,50,0);
				        s.addView(Tlayout1, 0, new Gallery.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
				        
					}
					if(tag.equals("Control Panel"))
					{

			        
			        final TableLayout Tlayout = new TableLayout(getApplicationContext());
			        
			        
			        TableRow Trow1 = new TableRow(getApplicationContext());
			        TextView textBox = new TextView(getApplicationContext()); 
			        textBox.setText("\tPlug 1");textBox.setTextColor(Color.WHITE);Trow1.addView(textBox);
			        textBox.setTypeface(Typeface.DEFAULT_BOLD);textBox.setTextSize(20);
			        power1.setTextSize(20);
			        power1.setTextColor(Color.WHITE);power1.setTypeface(Typeface.DEFAULT_BOLD);Trow1.addView(power1);
			          
			        button1.setTextOn(" On ");button1.setTextOff(" Off "); Trow1.addView(button1);
			        
			        
			        
			        button1.setOnClickListener(new View.OnClickListener() {
			             public void onClick(View v) {
			                 // Perform action on click
			            	
			            	 if (button1.getText().equals(" On "))
			            	 {
			            		 Message msg = new Message(homeosID, Message.Type.chat);
			            		 msg.setBody("<action subject=socket1 status=1/>");
			            		 connection.sendPacket(msg);
			            		 if(fb.isChecked()) postMessage("ON_MSG",power1.getText().toString());
			            		 if(tw.isChecked()) tweet(getFacebookMsg("ON_MSG",power1.getText().toString()));
			            	 }
			            	 else if (button1.getText().equals(" Off "))
			            	 {
				            	 Message msg = new Message(homeosID, Message.Type.chat);
				            	 msg.setBody("<action subject=socket1 status=0/>");
				            	 connection.sendPacket(msg);
				            	 if(fb.isChecked()) postMessage("OFF_MSG",power1.getText().toString());
			            		 if(tw.isChecked()) tweet(getFacebookMsg("OFF_MSG",power1.getText().toString()));
			            	 }
				            	 
			             }
			         });
			        
			        
			        
			        
			        Tlayout.addView(Trow1);
			        
			        
			        TableRow Trow2 = new TableRow(getApplicationContext());
			        TextView textBox2 = new TextView(getApplicationContext()); 
			        textBox2.setText("\tPlug 2");textBox2.setTextColor(Color.WHITE);Trow2.addView(textBox2);
			        textBox2.setTypeface(Typeface.DEFAULT_BOLD);power2.setTypeface(Typeface.DEFAULT_BOLD);
			        textBox2.setTextSize(20);
			        power2.setTextSize(20);
			        power2.setTextColor(Color.WHITE);Trow2.addView(power2);
			       
			        button2.setTextOn(" On ");button2.setTextOff(" Off "); Trow2.addView(button2);
			        
			        button2.setOnClickListener(new View.OnClickListener() {
			             public void onClick(View v) {
			                 // Perform action on click
			            	 if (button2.getText().equals(" On "))
			            	 {
			            	 Message msg = new Message(homeosID, Message.Type.chat);
			            	 msg.setBody("<action subject=socket2 status=1/>");
			            	 connection.sendPacket(msg);
			            	 if(fb.isChecked()) postMessage("ON_MSG",power2.getText().toString());
			            	 if(tw.isChecked()) tweet(getFacebookMsg("ON_MSG",power2.getText().toString()));
			            	 }
			            	 else if (button2.getText().equals(" Off "))
			            	 {
				            	 Message msg = new Message(homeosID, Message.Type.chat);
				            	 msg.setBody("<action subject=socket2 status=0/>");
				            	 connection.sendPacket(msg);
				            	 if(fb.isChecked()) postMessage("OFF_MSG",power2.getText().toString());
				            	 if(tw.isChecked()) tweet(getFacebookMsg("OFF_MSG",power2.getText().toString()));
			            	 }
			            	// Message msg = new Message(homeosID, Message.Type.chat);
			            	// msg.setBody("<get111111/>");
			            	// connection.sendPacket(msg);
				            	 
			             }
			         });
			        
			        
			        Tlayout.addView(Trow2);
			        
			        
			        TableRow Trow3 = new TableRow(getApplicationContext());
			        TextView textBox3 = new TextView(getApplicationContext()); 
			        textBox3.setText("\tPlug 3");textBox3.setTextColor(Color.WHITE);Trow3.addView(textBox3);
			        textBox3.setTypeface(Typeface.DEFAULT_BOLD);power3.setTypeface(Typeface.DEFAULT_BOLD);
			        textBox3.setTextSize(20);
			        power3.setTextSize(20);
			        power3.setTextColor(Color.WHITE);Trow3.addView(power3);
			       
			        button3.setTextOn(" On ");button3.setTextOff(" Off "); Trow3.addView(button3);
			        
			        button3.setOnClickListener(new View.OnClickListener() {
			             public void onClick(View v) {
			                 // Perform action on click
			            	 if (button3.getText().equals(" On "))
			            	 {
			            	 Message msg = new Message(homeosID, Message.Type.chat);
			            	 msg.setBody("<action subject=socket3 status=1/>");
			            	 connection.sendPacket(msg);
			            	 if(fb.isChecked()) postMessage("ON_MSG",power3.getText().toString());
			            	 if(tw.isChecked()) tweet(getFacebookMsg("ON_MSG",power3.getText().toString()));
			            	 }
			            	 else if (button3.getText().equals(" Off "))
			            	 {
				            	 Message msg = new Message(homeosID, Message.Type.chat);
				            	 msg.setBody("<action subject=socket3 status=0/>");
				            	 connection.sendPacket(msg);
				            	 if(fb.isChecked()) postMessage("OFF_MSG",power3.getText().toString());
				            	 if(tw.isChecked()) tweet(getFacebookMsg("OFF_MSG",power3.getText().toString()));
			            	 }
				            	 
			             }
			         });
			        
			        Tlayout.addView(Trow3);
			       
			        TableRow Trow4 = new TableRow(getApplicationContext());
			        TextView textBox4 = new TextView(getApplicationContext()); 
			        textBox4.setText("\tPlug 4");textBox4.setTextColor(Color.WHITE);Trow4.addView(textBox4);
			        textBox4.setTypeface(Typeface.DEFAULT_BOLD);power4.setTypeface(Typeface.DEFAULT_BOLD);
			        textBox4.setTextSize(20);
			        power4.setTextSize(20);
			        power4.setTextColor(Color.WHITE);Trow4.addView(power4);
			         
			        button4.setTextOn(" On ");button4.setTextOff(" Off "); Trow4.addView(button4);
			     
			        button4.setOnClickListener(new View.OnClickListener() {
			             public void onClick(View v) {
			                 // Perform action on click
			            	 if (button4.getText().equals(" On "))
			            	 {
			            	 Message msg = new Message(homeosID, Message.Type.chat);
			            	 msg.setBody("<action subject=socket4 status=1/>");
			            	 connection.sendPacket(msg);
			            	 if(fb.isChecked()) postMessage("ON_MSG",power4.getText().toString());
			            	 if(tw.isChecked()) tweet(getFacebookMsg("ON_MSG",power4.getText().toString()));
			            	 }
			            	 else if (button4.getText().equals(" Off "))
			            	 {
				            	 Message msg = new Message(homeosID, Message.Type.chat);
				            	 msg.setBody("<action subject=socket4 status=0/>");
				            	 connection.sendPacket(msg);
				            	 if(fb.isChecked()) postMessage("OFF_MSG",power4.getText().toString());
				            	 if(tw.isChecked()) tweet(getFacebookMsg("OFF_MSG",power4.getText().toString()));
			            	 }
				            	 
			             }
			         });
			        
			        Tlayout.addView(Trow4);
			     
			        TableRow Trow5 = new TableRow(getApplicationContext());
			        TextView textBox5 = new TextView(getApplicationContext()); 
			        textBox5.setText("\tPlug 5");textBox5.setTextColor(Color.WHITE);Trow5.addView(textBox5);
			        textBox5.setTypeface(Typeface.DEFAULT_BOLD);power5.setTypeface(Typeface.DEFAULT_BOLD);
			        textBox5.setTextSize(20);
			        power5.setTextSize(20);
			        power5.setTextColor(Color.WHITE);Trow5.addView(power5);
			        
			        button5.setTextOn(" On ");button5.setTextOff(" Off "); Trow5.addView(button5);
			      
			        button5.setOnClickListener(new View.OnClickListener() {
			             public void onClick(View v) {
			                 // Perform action on click
			            	 if (button5.getText().equals(" On "))
			            	 {
			            	 Message msg = new Message(homeosID, Message.Type.chat);
			            	 msg.setBody("<action subject=socket5 status=1/>");
			            	 connection.sendPacket(msg);
			            	 if(fb.isChecked()) postMessage("ON_MSG",power5.getText().toString());
			            	 if(tw.isChecked()) tweet(getFacebookMsg("ON_MSG",power5.getText().toString()));
			            	 }
			            	 else if (button5.getText().equals(" Off "))
			            	 {
				            	 Message msg = new Message(homeosID, Message.Type.chat);
				            	 msg.setBody("<action subject=socket5 status=0/>");
				            	 connection.sendPacket(msg);
				            	 if(fb.isChecked()) postMessage("OFF_MSG",power5.getText().toString());
				            	 if(tw.isChecked()) tweet(getFacebookMsg("OFF_MSG",power5.getText().toString()));
			            	 }
				            	 
			             }
			         });
			        
			        Tlayout.addView(Trow5);
			       TextView trash1 = new TextView(getApplicationContext());
			       
			       
			       
			        TableRow fbrow = new TableRow(getApplicationContext());
			        
			        TextView textBox6 = new TextView(getApplicationContext()); 
			        textBox6.setText("Facebook");textBox6.setTextColor(Color.WHITE);fbrow.addView(textBox6);
			        textBox6.setTypeface(Typeface.DEFAULT_BOLD);
			        textBox6.setTextSize(20);fbrow.addView(fb);
			        fb.setChecked(false); Tlayout.addView(fbrow);
			        
			       TableRow twitterrow = new TableRow(getApplicationContext());
			        
			        TextView textBox7 = new TextView(getApplicationContext()); 
			        textBox7.setText("Twitter");textBox7.setTextColor(Color.WHITE);twitterrow.addView(textBox7);
			        textBox7.setTypeface(Typeface.DEFAULT_BOLD);
			        textBox7.setTextSize(20);twitterrow.addView(tw);
			        tw.setChecked(false); Tlayout.addView(twitterrow);
			        
			        
			        
			        TableRow Trow6 = new TableRow(getApplicationContext());
			       Button logout = new Button(getApplicationContext());
			       logout.setText("Exit");
			       logout.setOnClickListener(new View.OnClickListener() {
			             public void onClick(View v) {
			                 // Perform action on click
			            	
			            	// clearCredentials();
			             	
			            stopService(myintent);
			            //connection.disconnect();
				        finish();	 
			             }
			         });
			       Trow6.addView(trash1);
			       Trow6.addView(logout); 
			       Tlayout.addView(Trow6);
			        
			        
			        
			        
			       Tlayout.setColumnStretchable(0, true);
			        Tlayout.setColumnStretchable(1, true);
			        Tlayout.setColumnStretchable(2, true);
			       // Tlayout.setPadding(50, 50,50,0);
			        
			        TableLayout.LayoutParams tableRowParams=
			        	  new TableLayout.LayoutParams
			        	  (TableLayout.LayoutParams.FILL_PARENT,TableLayout.LayoutParams.WRAP_CONTENT);

			        	int leftMargin=0;
			        	int topMargin=10;
			        	int rightMargin=0;
			        	int bottomMargin=10;

			        	tableRowParams.setMargins(leftMargin, topMargin, rightMargin, bottomMargin);
			        	tableRowParams.gravity = Gravity.CENTER_HORIZONTAL;
			        	Trow1.setLayoutParams(tableRowParams);
			        	Trow2.setLayoutParams(tableRowParams);
			        	Trow3.setLayoutParams(tableRowParams);
			        	Trow4.setLayoutParams(tableRowParams);
			        	Trow5.setLayoutParams(tableRowParams);
			        	Trow6.setLayoutParams(tableRowParams);
			        	
			        	fbrow.setLayoutParams(tableRowParams);
			        s.addView(Tlayout, 0, new Gallery.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
					}
					
					
					
					
					
					return s;}
			});
			tabHost.addTab(setContent);
		}

		private static View createTabView(final Context context, final String text) {
			View view = LayoutInflater.from(context).inflate(R.layout.tabs_bg, null);
			TextView tv = (TextView) view.findViewById(R.id.tabsText);
			tv.setText(text);
			return view;
		}		

		//*****************************************************************************************************
		
		
		
		
		
		
		
	 private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
	        @Override
	        public void onReceive(Context context, Intent intent) {
	        	updateUI(intent);       
	        }
	    };
	    
	    
	    
	    @Override
		public void onResume() {
			super.onResume();		
		//	startService(myintent);
		//	updateLoginStatus();
			registerReceiver(broadcastReceiver, new IntentFilter(BroadcastService.BROADCAST_ACTION));
		}
		
		@Override
		public void onPause() {
			super.onPause();
			unregisterReceiver(broadcastReceiver);
		//	stopService(myintent); 		
		}	
	    
		   private void updateUI(Intent intent) {
		    	//String counter = intent.getStringExtra("counter"); 
		    	String data = new String(intent.getStringExtra("data")); 
		    		
		    	//Log.d(TAG, counter);
		    	//data =  "<data><socket1><status>1</status><power>2.459912</power></socket1><socket2><status>1</status><power>45.12862</power></socket2><socket3><status>1</status><power>2.459912</power></socket3><socket4><status>1</status><power>2.459912</power></socket4><socket5><status>1</status><power>2.459912</power></socket5><temp>24.5  C</temp><light>5.2</light></data>";
		    	
		    	Log.d(TAG, data);
		    	
		    	
		    	try
		    	{
		    		Pattern p = Pattern.compile("<data><socket1><status>(\\d)</status><power>(\\d{1,}\\.\\d{1,})</power></socket1><socket2><status>(\\d)</status><power>(\\d{1,}\\.\\d{1,})</power></socket2><socket3><status>(\\d)</status><power>(\\d{1,}\\.\\d{1,})</power></socket3><socket4><status>(\\d)</status><power>(\\d{1,}\\.\\d{1,})</power></socket4><socket5><status>(\\d)</status><power>(\\d{1,}\\.\\d{1,})</power></socket5><temp>(\\d{1,}\\.\\d{1,}\\s{0,}\\w)</temp><light>(\\d{1,}\\.\\d{1,})</light></data>");
		    		Matcher m = p.matcher(data);//(\\d{1,}\\.\\d{1,}\\s\\sC)
		    		if(m.find())
		    		{
		    		
		    		power1.setText(m.group(2)+" W");
		    		power2.setText(m.group(4)+" W");
		    		power3.setText(m.group(6)+" W");
		    		power4.setText(m.group(8)+" W");
		    		power5.setText(m.group(10)+" W");
		    		if(first_load==0)
		    		{
		    		if(m.group(1).equals("1")) {button1.setChecked(true);button1.setText(" On ");} else {button1.setChecked(false);button1.setText(" Off ");}
		    		if(m.group(3).equals("1")) {button2.setChecked(true);button2.setText(" On ");} else {button2.setChecked(false);button2.setText(" Off ");}
		    		if(m.group(5).equals("1")) {button3.setChecked(true);button3.setText(" On ");} else {button3.setChecked(false);button3.setText(" Off ");}
		    		if(m.group(7).equals("1")) {button4.setChecked(true);button4.setText(" On ");} else {button4.setChecked(false);button4.setText(" Off ");}
		    		if(m.group(9).equals("1")) {button5.setChecked(true);button5.setText(" On ");} else {button5.setChecked(false);button5.setText(" Off ");}
		    		first_load++;
		    		
		    		}
		    		progressDialog.dismiss();
		    		temperature.setText(m.group(11));
		    		light.setText(m.group(12)+" lx");
		    		 
		    		float total = Math.round((Float.parseFloat(m.group(2)) +Float.parseFloat(m.group(4))+Float.parseFloat(m.group(6))
		    		+Float.parseFloat(m.group(8))+Float.parseFloat(m.group(10)) )* 100.0)  ;
		    		total /= 100.00;
		    		powerusage.setText(total+" W");
		    		
		    		for(int i=0; i < Different_Grap_Types.window_length - 1; i+=1) {
		    			Different_Grap_Types.powerlog[i] = Different_Grap_Types.powerlog[i+1];
		    		}
		    		Different_Grap_Types.powerlog[Different_Grap_Types.window_length - 1] = total ;
		    		
		    		}
		    		else 
		    		{//power1.setText(">"+data);
		    			
		    		}
		    	}	
		    	catch(Exception e){Log.d("PARSE ERROR",""+e);e.printStackTrace();}
		    	
		    	
		    	
		    }
}


